package org.dean.webapps.projectname.presentation.utils;

import org.apache.commons.lang.StringUtils;
import org.dean.webapps.projectname.constants.SessionConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.util.regex.Pattern;

import static org.dean.webapps.projectname.utils.URLUtils.getVelocityRedirectURL;

/**
 * Created by IntelliJ IDEA.
 * User: dean
 * Date: 8/25/11
 * Time: 4:01 PM
 * To change this template use File | Settings | File Templates.
 */
public class RequestUtils {

    public static HttpSession getSession(HttpServletRequest request) {
        return (request != null) ? request.getSession() : null;
    }

    public static HttpSession setCallBackUrl(HttpServletRequest request, String callBackUrl) {
        HttpSession session = getSession(request);

        session.setAttribute(SessionConstants.CALLBACK_URL_SESSION_KEY, callBackUrl);

        return session;
    }

    public static HttpSession setPreviousUrl(HttpServletRequest request, String previoiusUrl) {
        HttpSession session = getSession(request);

        session.setAttribute(SessionConstants.PREVIOUS_RUL_SESSION_KEY, previoiusUrl);

        return session;
    }

    public static String getUriFromRequest(HttpServletRequest request) {

        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        String contextPath = request.getContextPath();
        String servletPath = request.getServletPath();
        String pathInfo = request.getPathInfo();
        String queryString = request.getQueryString();

        // Reconstruct original requesting URL
        String url = scheme + "://" + serverName + ":" + serverPort + contextPath + servletPath;
        if (pathInfo != null) {
            url += pathInfo;
        }
        if (queryString != null) {
            url += "?" + queryString;
        }
        return url;

    }

    public static boolean isAjaxUrl(String url) {
        Pattern ajaxUrlPattern = Pattern.compile(
                String.format("%s", ".*/ajax/.*"));
        boolean rst = false;
        try {
            rst = ajaxUrlPattern.matcher(url).find();
        } catch (Exception e) {
            rst = false;
        } finally {
            return rst;
        }

    }

    public static String validRedirectUrl(String url){
        String redirectUrl = isAjaxUrl(url) ? "" : url;
        if (!StringUtils.isEmpty(redirectUrl)) {
            redirectUrl = getVelocityRedirectURL(redirectUrl);
        } else {
            redirectUrl = getVelocityRedirectURL("/");
        }

        return redirectUrl;
    }
}